#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab

from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division

'''
        @author: lbergesio

    Simple XML parser using minidom for this example

'''

from xml.dom import minidom

def getActionParams(action):
    atts=dict()
    l = action.attributes.items()
    for item in l:
        for att in ('type','id'):
            if item[0] == att:
                atts[item[0]] = item[1]
                break
    return atts


def getRspec(xml):
    return xml.getElementsByTagName('rspec')[0]

def getActions(rspec):
    return rspec.getElementsByTagName('action')

def parseVM(action):
    vmd=dict()
    for tag, name in (('name','Name'),('ram','RAM'),('hdd','HDD'),('os','OS'),
            ('version','Version'),('mac','MAC'),('ip','IP')):
        try:
            vmd[name] = action.getElementsByTagName('vm')[0].getElementsByTagName(tag)[0].toxml().replace('<'+tag+'>','').replace('</'+tag+'>','')
        except:
            vmd[name]=''
    return vmd


def parse(xml):
    data = minidom.parseString(xml)
    actions=list()
    actiond=dict()
    rspec=dict()
    for action in getActions(getRspec(data)):
        actiond['type'] = getActionParams(action)['type']
        actiond['id']   = getActionParams(action)['id']
        actiond['vm']   = parseVM(action)
        actions.append(actiond)

    rspec['actions'] = actions
    return rspec

if __name__ == "__main__":
    xml = open("example1.xml", "rb").read()
    print(parse(xml))
